﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XB.Core.MemoryStore.TimeSchduler
{
    public class SequentialTimer
    {
        private Timer _timer;
        private TimerCallback _callback;

        public int Duration { get; set; }

        public SequentialTimer(TimerCallback callback, int durationInMs)
        {
            // Create the Timer ensuring that it never fires. This ensures that
            // _timer refers to it BEFORE Tick is invoked by a thread pool thread
            _timer = new Timer(Tick, null, Timeout.Infinite, Timeout.Infinite);
            _callback = callback;

            Duration = durationInMs;

            // Now, _timer is assigned to, we can let the timer fire immediately
            _timer.Change(0, Timeout.Infinite);
        }

        /// <summary>
        /// Tick to call the registered callback method.
        /// </summary>
        /// <param name="state"></param>
        private void Tick(Object state)
        {
            _callback(state);
            _timer.Change(Duration, Timeout.Infinite);
        }
    }
}
